/**
 * @file device_service.cpp
 * @brief ONVIF设备管理服务实现
 * 
 * 本文件实现ONVIF Device Management Service规范
 * 负责设备信息查询、系统管理、网络配置等功能
 */

#include "device_service.h"
#include "soap/soap_message.h"
#include "network.h"
#include <sstream>
#include <chrono>
#include <iomanip>

namespace El {
namespace Onvif {

// 常量定义
static const size_t MAX_USERS = 32;

// 网络双工模式枚举
enum class NetworkDuplex {
    Half,
    Full
};

DeviceService::DeviceService() 
    : deviceInfo_{}
    , systemDateTime_{}
    , networkConfig_{}
    , configChangeCallback_(nullptr) {
    
    // 初始化默认设备信息
    deviceInfo_.manufacturer = "ONVIF Device";
    deviceInfo_.model = "Generic Camera";
    deviceInfo_.firmwareVersion = "1.0.0";
    deviceInfo_.serialNumber = "000000000001";
    deviceInfo_.hardwareId = "HW-001";
    
    // 初始化网络配置（使用动态IP检测）
    UpdateNetworkConfiguration();
    
    // 初始化系统时间
    UpdateSystemDateTime();
}



std::string DeviceService::HandleRequest(const SoapMessage& message, 
                                        const std::string& /*remoteAddr*/) {
    SoapMessageParser parser;
    
    try {
        if (message.action == "GetDeviceInformation") {
            return HandleGetDeviceInformation(message);
        } else if (message.action == "GetSystemDateAndTime") {
            return HandleGetSystemDateAndTime(message);
        } else if (message.action == "SetSystemDateAndTime") {
            return HandleSetSystemDateAndTime(message);
        } else if (message.action == "GetCapabilities") {
            return HandleGetCapabilities(message);
        } else if (message.action == "GetServices") {
            return HandleGetServices(message);
        } else if (message.action == "GetUsers") {
            return HandleGetUsers(message);
        } else if (message.action == "CreateUsers") {
            return HandleCreateUsers(message);
        } else if (message.action == "DeleteUsers") {
            return HandleDeleteUsers(message);
        } else if (message.action == "GetNetworkInterfaces") {
            return HandleGetNetworkInterfaces(message);
        } else if (message.action == "SetNetworkInterfaces") {
            return HandleSetNetworkInterfaces(message);
        } else if (message.action == "GetNetworkProtocols") {
            return HandleGetNetworkProtocols(message);
        } else if (message.action == "SetNetworkProtocols") {
            return HandleSetNetworkProtocols(message);
        } else if (message.action == "GetDNS") {
            return HandleGetDNS(message);
        } else if (message.action == "SetDNS") {
            return HandleSetDNS(message);
        } else if (message.action == "GetNTP") {
            return HandleGetNTP(message);
        } else if (message.action == "SetNTP") {
            return HandleSetNTP(message);
        } else if (message.action == "GetHostname") {
            return HandleGetHostname(message);
        } else if (message.action == "SetHostname") {
            return HandleSetHostname(message);
        } else if (message.action == "GetScopes") {
            return HandleGetScopes(message);
        } else if (message.action == "SetScopes") {
            return HandleSetScopes(message);
        } else if (message.action == "SystemReboot") {
            return HandleSystemReboot(message);
        } else if (message.action == "RestoreSystem") {
            return HandleRestoreSystem(message);
        }
        
        return parser.GenerateSoapFault(SoapError::NotSupported, 
                                       "Unknown device action: " + message.action);
    } catch (const std::exception& e) {
        return parser.GenerateSoapFault(SoapError::InternalError, e.what());
    }
}

void DeviceService::SetDeviceInformation(const DeviceInformation& info) {
    std::lock_guard<std::mutex> lock(deviceMutex_);
    deviceInfo_ = info;
    
    if (configChangeCallback_) {
        configChangeCallback_("DeviceInformation");
    }
}

DeviceInformation DeviceService::GetDeviceInformation() const {
    std::lock_guard<std::mutex> lock(deviceMutex_);
    return deviceInfo_;
}

void DeviceService::SetNetworkConfiguration(const NetworkInterface& config) {
    std::lock_guard<std::mutex> lock(deviceMutex_);
    networkConfig_ = config;
    
    if (configChangeCallback_) {
        configChangeCallback_("NetworkConfiguration");
    }
}

NetworkInterface DeviceService::GetNetworkConfiguration() const {
    std::lock_guard<std::mutex> lock(deviceMutex_);
    return networkConfig_;
}

void DeviceService::SetSystemDateTime(const SystemDateTime& dateTime) {
    std::lock_guard<std::mutex> lock(systemMutex_);
    systemDateTime_ = dateTime;
    
    if (configChangeCallback_) {
        configChangeCallback_("SystemDateTime");
    }
}

SystemDateTime DeviceService::GetSystemDateTime() const {
    std::lock_guard<std::mutex> lock(systemMutex_);
    return systemDateTime_;
}

void DeviceService::AddUser(const User& user) {
    std::lock_guard<std::mutex> lock(usersMutex_);
    
    // 检查用户数量限制
    if (users_.size() >= MAX_USERS) {
        throw std::runtime_error("Maximum number of users exceeded");
    }
    
    // 检查用户名是否已存在
    for (const auto& existingUser : users_) {
        if (existingUser.username == user.username) {
            throw std::runtime_error("User already exists");
        }
    }
    
    users_.push_back(user);
    
    if (configChangeCallback_) {
        configChangeCallback_("Users");
    }
}

void DeviceService::RemoveUser(const std::string& username) {
    std::lock_guard<std::mutex> lock(usersMutex_);
    
    auto it = std::find_if(users_.begin(), users_.end(),
                          [&username](const User& user) {
                              return user.username == username;
                          });
    
    if (it != users_.end()) {
        users_.erase(it);
        
        if (configChangeCallback_) {
            configChangeCallback_("Users");
        }
    }
}

std::vector<User> DeviceService::GetUsers() const {
    std::lock_guard<std::mutex> lock(usersMutex_);
    return users_;
}

void DeviceService::SetConfigChangeCallback(ConfigChangeCallback callback) {
    configChangeCallback_ = callback;
}

// 私有方法实现
void DeviceService::UpdateSystemDateTime() {
    auto now = std::chrono::system_clock::now();
    
    std::lock_guard<std::mutex> lock(systemMutex_);
    systemDateTime_.dateTimeType = SystemDateTime::DateTimeType::NTP;
    systemDateTime_.daylightSavings = false;
    systemDateTime_.timeZone = "UTC";
    systemDateTime_.utcDateTime = now;
}

std::string DeviceService::HandleGetDeviceInformation(const SoapMessage& /*message*/) {
    std::lock_guard<std::mutex> lock(deviceMutex_);
    
    std::ostringstream response;
    response << "    <tds:GetDeviceInformationResponse>\n"
             << "      <tds:Manufacturer>" << EscapeXml(deviceInfo_.manufacturer) << "</tds:Manufacturer>\n"
             << "      <tds:Model>" << EscapeXml(deviceInfo_.model) << "</tds:Model>\n"
             << "      <tds:FirmwareVersion>" << EscapeXml(deviceInfo_.firmwareVersion) << "</tds:FirmwareVersion>\n"
             << "      <tds:SerialNumber>" << EscapeXml(deviceInfo_.serialNumber) << "</tds:SerialNumber>\n"
             << "      <tds:HardwareId>" << EscapeXml(deviceInfo_.hardwareId) << "</tds:HardwareId>\n"
             << "    </tds:GetDeviceInformationResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "GetDeviceInformationResponse");
}

std::string DeviceService::HandleGetSystemDateAndTime(const SoapMessage& /*message*/) {
    UpdateSystemDateTime(); // 更新当前时间
    
    std::lock_guard<std::mutex> lock(systemMutex_);
    
    // 转换时间点为tm结构
    auto time_t = std::chrono::system_clock::to_time_t(systemDateTime_.utcDateTime);
    auto tm = *std::gmtime(&time_t);
    
    // 将枚举转换为字符串
    std::string dateTimeTypeStr = (systemDateTime_.dateTimeType == SystemDateTime::DateTimeType::NTP) ? "NTP" : "Manual";
    
    std::ostringstream response;
    response << "    <tds:GetSystemDateAndTimeResponse>\n"
             << "      <tds:SystemDateAndTime>\n"
             << "        <tt:DateTimeType>" << EscapeXml(dateTimeTypeStr) << "</tt:DateTimeType>\n"
             << "        <tt:DaylightSavings>" << (systemDateTime_.daylightSavings ? "true" : "false") << "</tt:DaylightSavings>\n"
             << "        <tt:TimeZone>\n"
             << "          <tt:TZ>" << EscapeXml(systemDateTime_.timeZone) << "</tt:TZ>\n"
             << "        </tt:TimeZone>\n"
             << "        <tt:UTCDateTime>\n"
             << "          <tt:Time>\n"
             << "            <tt:Hour>" << tm.tm_hour << "</tt:Hour>\n"
             << "            <tt:Minute>" << tm.tm_min << "</tt:Minute>\n"
             << "            <tt:Second>" << tm.tm_sec << "</tt:Second>\n"
             << "          </tt:Time>\n"
             << "          <tt:Date>\n"
             << "            <tt:Year>" << (tm.tm_year + 1900) << "</tt:Year>\n"
             << "            <tt:Month>" << (tm.tm_mon + 1) << "</tt:Month>\n"
             << "            <tt:Day>" << tm.tm_mday << "</tt:Day>\n"
             << "          </tt:Date>\n"
             << "        </tt:UTCDateTime>\n"
             << "      </tds:SystemDateAndTime>\n"
             << "    </tds:GetSystemDateAndTimeResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "GetSystemDateAndTimeResponse");
}

std::string DeviceService::HandleSetSystemDateAndTime(const SoapMessage& /*message*/) {
    // 这里应该解析请求中的时间设置，简化实现只返回成功
    std::ostringstream response;
    response << "    <tds:SetSystemDateAndTimeResponse/>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "SetSystemDateAndTimeResponse");
}

std::string DeviceService::HandleGetCapabilities(const SoapMessage& /*message*/) {
    std::string currentIp = GetCurrentIpAddress();
    
    std::ostringstream response;
    response << "    <tds:GetCapabilitiesResponse>\n"
             << "      <tds:Capabilities>\n"
             << "        <tt:Device>\n"
             << "          <tt:XAddr>http://" << currentIp << "/onvif/device_service</tt:XAddr>\n"
             << "          <tt:Network>\n"
             << "            <tt:IPFilter>false</tt:IPFilter>\n"
             << "            <tt:ZeroConfiguration>false</tt:ZeroConfiguration>\n"
             << "            <tt:IPVersion6>false</tt:IPVersion6>\n"
             << "            <tt:DynDNS>false</tt:DynDNS>\n"
             << "            <tt:Dot11Configuration>false</tt:Dot11Configuration>\n"
             << "          </tt:Network>\n"
             << "          <tt:System>\n"
             << "            <tt:DiscoveryResolve>false</tt:DiscoveryResolve>\n"
             << "            <tt:DiscoveryBye>false</tt:DiscoveryBye>\n"
             << "            <tt:RemoteDiscovery>false</tt:RemoteDiscovery>\n"
             << "            <tt:SystemBackup>false</tt:SystemBackup>\n"
             << "            <tt:SystemLogging>false</tt:SystemLogging>\n"
             << "            <tt:FirmwareUpgrade>false</tt:FirmwareUpgrade>\n"
             << "            <tt:HttpFirmwareUpgrade>false</tt:HttpFirmwareUpgrade>\n"
             << "            <tt:HttpSystemBackup>false</tt:HttpSystemBackup>\n"
             << "            <tt:HttpSystemLogging>false</tt:HttpSystemLogging>\n"
             << "            <tt:HttpSupportInformation>false</tt:HttpSupportInformation>\n"
             << "          </tt:System>\n"
             << "          <tt:Security>\n"
             << "            <tt:TLS1.0>false</tt:TLS1.0>\n"
             << "            <tt:TLS1.1>false</tt:TLS1.1>\n"
             << "            <tt:TLS1.2>true</tt:TLS1.2>\n"
             << "            <tt:OnboardKeyGeneration>false</tt:OnboardKeyGeneration>\n"
             << "            <tt:AccessPolicyConfig>false</tt:AccessPolicyConfig>\n"
             << "            <tt:DefaultAccessPolicy>false</tt:DefaultAccessPolicy>\n"
             << "            <tt:Dot1X>false</tt:Dot1X>\n"
             << "            <tt:RemoteUserHandling>false</tt:RemoteUserHandling>\n"
             << "            <tt:X.509Token>false</tt:X.509Token>\n"
             << "            <tt:SAMLToken>false</tt:SAMLToken>\n"
             << "            <tt:KerberosToken>false</tt:KerberosToken>\n"
             << "            <tt:UsernameToken>true</tt:UsernameToken>\n"
             << "            <tt:HttpDigest>false</tt:HttpDigest>\n"
             << "            <tt:RELToken>false</tt:RELToken>\n"
             << "          </tt:Security>\n"
             << "        </tt:Device>\n"
             << "        <tt:Media>\n"
             << "          <tt:XAddr>http://" << currentIp << "/onvif/media_service</tt:XAddr>\n"
             << "          <tt:StreamingCapabilities>\n"
             << "            <tt:RTPMulticast>false</tt:RTPMulticast>\n"
             << "            <tt:RTP_TCP>true</tt:RTP_TCP>\n"
             << "            <tt:RTP_RTSP_TCP>true</tt:RTP_RTSP_TCP>\n"
             << "          </tt:StreamingCapabilities>\n"
             << "        </tt:Media>\n"
             << "        <tt:PTZ>\n"
             << "          <tt:XAddr>http://" << currentIp << "/onvif/ptz_service</tt:XAddr>\n"
             << "        </tt:PTZ>\n"
             << "      </tds:Capabilities>\n"
             << "    </tds:GetCapabilitiesResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "GetCapabilitiesResponse");
}

std::string DeviceService::HandleGetServices(const SoapMessage& /*message*/) {
    std::string currentIp = GetCurrentIpAddress();
    
    std::ostringstream response;
    response << "    <tds:GetServicesResponse>\n"
             << "      <tds:Service>\n"
             << "        <tds:Namespace>http://www.onvif.org/ver10/device/wsdl</tds:Namespace>\n"
             << "        <tds:XAddr>http://" << currentIp << "/onvif/device_service</tds:XAddr>\n"
             << "        <tds:Version>\n"
             << "          <tt:Major>2</tt:Major>\n"
             << "          <tt:Minor>0</tt:Minor>\n"
             << "        </tds:Version>\n"
             << "      </tds:Service>\n"
             << "      <tds:Service>\n"
             << "        <tds:Namespace>http://www.onvif.org/ver10/media/wsdl</tds:Namespace>\n"
             << "        <tds:XAddr>http://" << currentIp << "/onvif/media_service</tds:XAddr>\n"
             << "        <tds:Version>\n"
             << "          <tt:Major>2</tt:Major>\n"
             << "          <tt:Minor>0</tt:Minor>\n"
             << "        </tds:Version>\n"
             << "      </tds:Service>\n"
             << "      <tds:Service>\n"
             << "        <tds:Namespace>http://www.onvif.org/ver20/ptz/wsdl</tds:Namespace>\n"
             << "        <tds:XAddr>http://" << currentIp << "/onvif/ptz_service</tds:XAddr>\n"
             << "        <tds:Version>\n"
             << "          <tt:Major>2</tt:Major>\n"
             << "          <tt:Minor>0</tt:Minor>\n"
             << "        </tds:Version>\n"
             << "      </tds:Service>\n"
             << "    </tds:GetServicesResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "GetServicesResponse");
}

std::string DeviceService::HandleGetUsers(const SoapMessage& /*message*/) {
    std::lock_guard<std::mutex> lock(usersMutex_);
    
    std::ostringstream response;
    response << "    <tds:GetUsersResponse>\n";
    
    for (const auto& user : users_) {
        response << "      <tds:User>\n"
                 << "        <tt:Username>" << EscapeXml(user.username) << "</tt:Username>\n"
                 << "        <tt:Password></tt:Password>\n" // 不返回密码
                 << "        <tt:UserLevel>" << static_cast<int>(user.userLevel) << "</tt:UserLevel>\n"
                 << "      </tds:User>\n";
    }
    
    response << "    </tds:GetUsersResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "GetUsersResponse");
}

std::string DeviceService::HandleCreateUsers(const SoapMessage& /*message*/) {
    // 简化实现，实际应该解析请求中的用户信息
    std::ostringstream response;
    response << "    <tds:CreateUsersResponse/>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "CreateUsersResponse");
}

std::string DeviceService::HandleDeleteUsers(const SoapMessage& /*message*/) {
    // 简化实现，实际应该解析请求中的用户名
    std::ostringstream response;
    response << "    <tds:DeleteUsersResponse/>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "DeleteUsersResponse");
}

std::string DeviceService::HandleGetNetworkInterfaces(const SoapMessage& /*message*/) {
    std::lock_guard<std::mutex> lock(deviceMutex_);
    
    std::ostringstream response;
    response << "    <tds:GetNetworkInterfacesResponse>\n"
             << "      <tds:NetworkInterfaces token=\"" << EscapeXml(networkConfig_.token) << "\">\n"
             << "        <tt:Enabled>" << (networkConfig_.enabled ? "true" : "false") << "</tt:Enabled>\n"
             << "        <tt:Info>\n"
                           << "          <tt:Name>" << EscapeXml(networkConfig_.token) << "</tt:Name>\n"
             << "          <tt:HwAddress>" << EscapeXml(networkConfig_.macAddress) << "</tt:HwAddress>\n"
             << "          <tt:MTU>" << networkConfig_.mtu << "</tt:MTU>\n"
             << "        </tt:Info>\n"
             << "        <tt:IPv4>\n"
             << "          <tt:Enabled>" << (networkConfig_.enabled ? "true" : "false") << "</tt:Enabled>\n"
             << "          <tt:Config>\n"
             << "            <tt:Manual>\n"
             << "              <tt:Address>" << EscapeXml(networkConfig_.ipAddress) << "</tt:Address>\n"
             << "              <tt:PrefixLength>" << networkConfig_.prefixLength << "</tt:PrefixLength>\n"
             << "            </tt:Manual>\n"
             << "            <tt:DHCP>" << (networkConfig_.dhcp ? "true" : "false") << "</tt:DHCP>\n"
             << "          </tt:Config>\n"
             << "        </tt:IPv4>\n"
             << "      </tds:NetworkInterfaces>\n"
             << "    </tds:GetNetworkInterfacesResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "GetNetworkInterfacesResponse");
}

std::string DeviceService::HandleSetNetworkInterfaces(const SoapMessage& /*message*/) {
    // 简化实现，实际应该解析请求中的网络配置
    std::ostringstream response;
    response << "    <tds:SetNetworkInterfacesResponse>\n"
             << "      <tds:RebootNeeded>false</tds:RebootNeeded>\n"
             << "    </tds:SetNetworkInterfacesResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "SetNetworkInterfacesResponse");
}

std::string DeviceService::HandleGetNetworkProtocols(const SoapMessage& /*message*/) {
    std::ostringstream response;
    response << "    <tds:GetNetworkProtocolsResponse>\n"
             << "      <tds:NetworkProtocols>\n"
             << "        <tt:Name>HTTP</tt:Name>\n"
             << "        <tt:Enabled>true</tt:Enabled>\n"
             << "        <tt:Port>80</tt:Port>\n"
             << "      </tds:NetworkProtocols>\n"
             << "      <tds:NetworkProtocols>\n"
             << "        <tt:Name>HTTPS</tt:Name>\n"
             << "        <tt:Enabled>false</tt:Enabled>\n"
             << "        <tt:Port>443</tt:Port>\n"
             << "      </tds:NetworkProtocols>\n"
             << "      <tds:NetworkProtocols>\n"
             << "        <tt:Name>RTSP</tt:Name>\n"
             << "        <tt:Enabled>true</tt:Enabled>\n"
             << "        <tt:Port>554</tt:Port>\n"
             << "      </tds:NetworkProtocols>\n"
             << "    </tds:GetNetworkProtocolsResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "GetNetworkProtocolsResponse");
}

std::string DeviceService::HandleSetNetworkProtocols(const SoapMessage& /*message*/) {
    std::ostringstream response;
    response << "    <tds:SetNetworkProtocolsResponse/>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "SetNetworkProtocolsResponse");
}

std::string DeviceService::HandleGetDNS(const SoapMessage& /*message*/) {
    std::ostringstream response;
    response << "    <tds:GetDNSResponse>\n"
             << "      <tds:DNSInformation>\n"
             << "        <tt:FromDHCP>false</tt:FromDHCP>\n"
             << "        <tt:DNSManual>\n"
             << "          <tt:Type>IPv4</tt:Type>\n"
             << "          <tt:IPv4Address>8.8.8.8</tt:IPv4Address>\n"
             << "        </tt:DNSManual>\n"
             << "        <tt:DNSManual>\n"
             << "          <tt:Type>IPv4</tt:Type>\n"
             << "          <tt:IPv4Address>8.8.4.4</tt:IPv4Address>\n"
             << "        </tt:DNSManual>\n"
             << "      </tds:DNSInformation>\n"
             << "    </tds:GetDNSResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "GetDNSResponse");
}

std::string DeviceService::HandleSetDNS(const SoapMessage& /*message*/) {
    std::ostringstream response;
    response << "    <tds:SetDNSResponse/>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "SetDNSResponse");
}

std::string DeviceService::HandleGetNTP(const SoapMessage& /*message*/) {
    std::ostringstream response;
    response << "    <tds:GetNTPResponse>\n"
             << "      <tds:NTPInformation>\n"
             << "        <tt:FromDHCP>false</tt:FromDHCP>\n"
             << "        <tt:NTPManual>\n"
             << "          <tt:Type>IPv4</tt:Type>\n"
             << "          <tt:IPv4Address>pool.ntp.org</tt:IPv4Address>\n"
             << "        </tt:NTPManual>\n"
             << "      </tds:NTPInformation>\n"
             << "    </tds:GetNTPResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "GetNTPResponse");
}

std::string DeviceService::HandleSetNTP(const SoapMessage& /*message*/) {
    std::ostringstream response;
    response << "    <tds:SetNTPResponse/>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "SetNTPResponse");
}

std::string DeviceService::HandleGetHostname(const SoapMessage& /*message*/) {
    std::ostringstream response;
    response << "    <tds:GetHostnameResponse>\n"
             << "      <tds:HostnameInformation>\n"
             << "        <tt:FromDHCP>false</tt:FromDHCP>\n"
             << "        <tt:Name>onvif-device</tt:Name>\n"
             << "      </tds:HostnameInformation>\n"
             << "    </tds:GetHostnameResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "GetHostnameResponse");
}

std::string DeviceService::HandleSetHostname(const SoapMessage& /*message*/) {
    std::ostringstream response;
    response << "    <tds:SetHostnameResponse/>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "SetHostnameResponse");
}

std::string DeviceService::HandleGetScopes(const SoapMessage& /*message*/) {
    std::ostringstream response;
    response << "    <tds:GetScopesResponse>\n"
             << "      <tds:Scopes>\n"
             << "        <tt:ScopeDef>Fixed</tt:ScopeDef>\n"
             << "        <tt:ScopeItem>onvif://www.onvif.org/type/video_encoder</tt:ScopeItem>\n"
             << "      </tds:Scopes>\n"
             << "      <tds:Scopes>\n"
             << "        <tt:ScopeDef>Fixed</tt:ScopeDef>\n"
             << "        <tt:ScopeItem>onvif://www.onvif.org/hardware/generic</tt:ScopeItem>\n"
             << "      </tds:Scopes>\n"
             << "    </tds:GetScopesResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "GetScopesResponse");
}

std::string DeviceService::HandleSetScopes(const SoapMessage& /*message*/) {
    std::ostringstream response;
    response << "    <tds:SetScopesResponse/>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "SetScopesResponse");
}

std::string DeviceService::HandleSystemReboot(const SoapMessage& /*message*/) {
    std::ostringstream response;
    response << "    <tds:SystemRebootResponse>\n"
             << "      <tds:Message>System will reboot in 5 seconds</tds:Message>\n"
             << "    </tds:SystemRebootResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "SystemRebootResponse");
}

std::string DeviceService::HandleRestoreSystem(const SoapMessage& /*message*/) {
    std::ostringstream response;
    response << "    <tds:RestoreSystemResponse>\n"
             << "      <tds:Message>System restored to factory defaults</tds:Message>\n"
             << "    </tds:RestoreSystemResponse>\n";
    
    SoapMessageParser parser;
    return parser.GenerateSoapResponse(response.str(), "RestoreSystemResponse");
}

std::string DeviceService::EscapeXml(const std::string& input) const {
    std::string escaped = input;
    
    // 替换XML特殊字符
    std::string::size_type pos = 0;
    while ((pos = escaped.find('&', pos)) != std::string::npos) {
        escaped.replace(pos, 1, "&amp;");
        pos += 5;
    }
    
    pos = 0;
    while ((pos = escaped.find('<', pos)) != std::string::npos) {
        escaped.replace(pos, 1, "&lt;");
        pos += 4;
    }
    
    pos = 0;
    while ((pos = escaped.find('>', pos)) != std::string::npos) {
        escaped.replace(pos, 1, "&gt;");
        pos += 4;
    }
    
    pos = 0;
    while ((pos = escaped.find('"', pos)) != std::string::npos) {
        escaped.replace(pos, 1, "&quot;");
        pos += 6;
    }
    
    pos = 0;
    while ((pos = escaped.find('\'', pos)) != std::string::npos) {
        escaped.replace(pos, 1, "&apos;");
        pos += 6;
    }
    
    return escaped;
}

void DeviceService::UpdateNetworkConfiguration() {
    try {
        // 获取网络管理器实例
        El::Network::Network& networkManager = El::Network::Network::GetInstance();
        
        // 获取默认网络接口名称
        auto& configManager = Common::ConfigManager::GetInstance();
        auto networkConfig = configManager.GetConfig("/network");
        std::string defaultInterfaceName = networkConfig.value("default_interface", "eth0");
        
        // 如果没有找到默认网卡，使用eth0作为默认值
        if (defaultInterfaceName.empty()) {
            defaultInterfaceName = "eth0";
        }
        
        // 获取该接口的详细信息（仍需要Network服务获取实时状态）
        nlohmann::json ifStatus;
        networkManager.GetInterfaceStatus(defaultInterfaceName, ifStatus);
        std::string ipAddress = networkManager.GetInterfaceIpAddress(defaultInterfaceName);
        
        // 使用获取到的接口信息
        networkConfig_.token = defaultInterfaceName;
        networkConfig_.enabled = ifStatus.value("up", false);
        networkConfig_.ipAddress = ipAddress;
        
        // 获取网关信息
        if (networkConfig.contains("interfaces") && 
            networkConfig["interfaces"].contains(defaultInterfaceName) &&
            networkConfig["interfaces"][defaultInterfaceName].contains("ipv4") &&
            networkConfig["interfaces"][defaultInterfaceName]["ipv4"].contains("gateway")) {
            networkConfig_.gateway = networkConfig["interfaces"][defaultInterfaceName]["ipv4"]["gateway"].get<std::string>();
        } else {
            networkConfig_.gateway = "192.168.1.1";
        }
        
        networkConfig_.macAddress = "00:11:22:33:44:55"; // 默认MAC地址
        networkConfig_.prefixLength = 24; // 默认为24位前缀
        
        // 设置DHCP模式
        bool dhcpMode = true; // 默认使用DHCP
        if (networkConfig.contains("interfaces") && 
            networkConfig["interfaces"].contains(defaultInterfaceName) &&
            networkConfig["interfaces"][defaultInterfaceName].contains("mode")) {
            std::string mode = networkConfig["interfaces"][defaultInterfaceName]["mode"].get<std::string>();
            dhcpMode = (mode == "dhcp");
        }
        networkConfig_.dhcp = dhcpMode;
        
        // 设置DNS服务器
        auto dnsServers = networkManager.GetDnsServers();
        if (!dnsServers.empty()) {
            networkConfig_.dns = dnsServers;
        } else {
            networkConfig_.dns = {"8.8.8.8", "8.8.4.4"};
        }
        networkConfig_.mtu = 1500;
        
        // 更新当前IP地址缓存
        currentIpAddress_ = ipAddress;
        
    } catch (const std::exception& e) {
        // 如果获取失败，使用默认配置
        networkConfig_.token = "eth0";
        networkConfig_.enabled = true;
        networkConfig_.dhcp = true;
        networkConfig_.ipAddress = "192.168.1.100";
        networkConfig_.prefixLength = 24;
        networkConfig_.gateway = "192.168.1.1";
        networkConfig_.dns = {"8.8.8.8", "8.8.4.4"};
        networkConfig_.macAddress = "00:11:22:33:44:55";
        networkConfig_.mtu = 1500;
        currentIpAddress_ = networkConfig_.ipAddress;
    }
}

std::string DeviceService::GetCurrentIpAddress() const {
    // 如果缓存的IP地址为空，尝试实时获取
    if (currentIpAddress_.empty()) {
        try {
            El::Network::Network& networkManager = El::Network::Network::GetInstance();
            std::string defaultInterfaceName = networkManager.GetDefaultInterfaceName();
            if (!defaultInterfaceName.empty()) {
                std::string ipAddress = networkManager.GetInterfaceIpAddress(defaultInterfaceName);
                if (!ipAddress.empty() && ipAddress != "127.0.0.1") {
                    return ipAddress;
                }
            }
        } catch (const std::exception& e) {
            // 获取失败，返回配置中的IP
        }
        return networkConfig_.ipAddress;
    }
    return currentIpAddress_;
}

int DeviceService::CalculatePrefixLength(const std::string& netmask) const {
    if (netmask.empty()) return 24;
    
    // 简单的子网掩码到前缀长度转换
    if (netmask == "255.255.255.0") return 24;
    if (netmask == "255.255.0.0") return 16;
    if (netmask == "255.0.0.0") return 8;
    if (netmask == "255.255.255.128") return 25;
    if (netmask == "255.255.255.192") return 26;
    if (netmask == "255.255.255.224") return 27;
    if (netmask == "255.255.255.240") return 28;
    if (netmask == "255.255.255.248") return 29;
    if (netmask == "255.255.255.252") return 30;
    
    return 24; // 默认值
}

} // namespace Onvif
} // namespace El 